<template>
  <div class="warpper-box sendSalary">
    <a-card style="margin-top: 10px;">
      <div style="display: flex;justify-content: flex-start;align-items: flex-start;">
        <form-create v-model="params.fApi" :rule="params.rule" :option="params.option" @btn-search-click="loadTable(true)"
          @btn-reset-click="reset" />
        <span style="padding: 5px 0 0 0;">
          <!-- <a-button type="primary" @click="importVisible = true">导入计薪人员</a-button> -->
          <a-button type="primary" @click="exportSalary">导出发薪明细</a-button>
          <a-button type="danger" @click="delSalary" :disabled="selectedRowKeys.length == 0">删除计薪人员</a-button>
        </span>
      </div>
      <a-alert message="计薪工资" type="success">
        <p slot="description" style="margin: 0;">
          <span style="color: #039D12;font-size: 24px;padding-left: 10px">{{ table.pagination.total }}</span> 人
        </p>
      </a-alert>
      <a-table :columns="table.columns" :data-source="table.loadData" :pagination="table.pagination"
        @change="handleTableChange" rowKey="detailId"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :scroll="{ x: tableWidth }">
      </a-table>
      <div style="height: 60px;"></div>
    </a-card>
    <!-- 导入计薪人员 -->
    <a-modal v-model="importVisible" title="导入计薪人员" width="540px" :footer="null">
      <a-alert message="第一步：下载导入信息模板；模版内的表头请勿改动，防止导入时出错。" type="info" />
      <a-button type="primary" @click="downloadSalary" ghost style=";margin: 20px 0;width: 160px;">下载模板</a-button>
      <a-alert message="第二步：批量导入人员数据；请填写完整的员工信息。" type="info" />
      <a-button type="primary" @click="importSalary" style="margin: 20px 0;width: 160px;">上传文件</a-button>
      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileExcel"
        @change="importSalaryHandle" style="display: none;" />
    </a-modal>
    <!-- 返回||提交 -->
    <a-card class="footBtn" hoverable :bordered="false">
      <a-button key="back" icon="logout" class="ant-btn-warning" @click="goBack">返回</a-button>
      <!-- <a-button type="primary" icon="file-done" @click="submit" style="margin-left: 10px;">提交</a-button> -->
    </a-card>
  </div>
</template>

<script>
import store from '@/store'
import {
  PARAMS_SALARY_DETAIL,
  COLUMNS_SENDSALARY_DETAIL
} from "./form"
import {
  OPTION_BLOCK,
  OPTION_INLINE
} from "../base_form"
import {
  getTableDetailPage,
  downTemplate,
  importSalaryDetail,
  batchDeleteSalary,
  exportExcelDetails
} from "@/api/human/salaryPaySendSalary"
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'sendSalaryDetail',
  components: {
    
  },
  data() {
    return {
      params: {
        fApi: {},
        rule: PARAMS_SALARY_DETAIL,
        option: OPTION_INLINE,
      },
      table: {
        columns: [],
        loadData: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      tableWidth: 1600, // 表格宽度
      selectedRowKeys: [], // 选择的table数据id
      selectedRows: [], // 选择的table数据
      pagination: { current: 1, pageSize: 10 },

      enterpriseId: "", // 企业id
      orderId: "", // 订单id

      importVisible: false, // 导入计薪人员显示
    }
  },
  filters: {
    filterMore(value, num) {
      if (!value) return ''
      if (value.length > num) {
        return value.slice(0, num) + '...'
      }
      return value
    }
  },
  mounted() {
    window.addEventListener('keyup', this.keyDown);
  },
  destroyed() {
    window.removeEventListener('keyup', this.keyDown);
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    })
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {

  },
  activated() {
    this.enterpriseId = this.$route.query.enterpriseId || "";
    this.orderId = this.$route.query.orderId || "";
    this.loadTable(true);
  },
  methods: {
    // table复选框选择
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 获取企业员工列表
    async loadTable(flag) {
      // table配置项重置
      this.table.columns = [
        {
          title: '姓名',
          dataIndex: 'userName',
          fixed: 'left'
        },
        {
          title: '身份证号',
          dataIndex: 'idCard',
          width: 200
        },
        {
          title: '结算金额',
          dataIndex: 'settleAmount',
        },
        {
          title: '服务费',
          dataIndex: 'serviceFeeAmount',
        },
        {
          title: '结算卡号',
          dataIndex: 'bankCard',
          width: 200
        },
        {
          title: '在职人员',
          dataIndex: 'staffId',
          customRender: (text, row, index) => {
            if (text) {
              return '是'
            } else {
              return '否'
            }
          },
        },
        {
          title: '结算状态',
          dataIndex: 'settleStatus',
          customRender: (text, row, index) => {
            if (text == 1) {
              return '待审核'
            } else if (text == 2) {
              return '结算中'
            } else if (text == 3) {
              return '结算成功'
            } else if (text == 4) {
              return '作废'
            } else if (text == 5) {
              return '结算失败'
            } else if (text == 6) {
              return '已驳回'
            }
            return ''
          },
        },
        {
          title: '失败原因',
          dataIndex: 'cooperationName',
        },
        {
          title: '结算时间',
          dataIndex: 'settleNum',
        },
        {
          title: '应发工资',
          dataIndex: 'shouldBeAmount',
        },
        {
          title: '个税',
          dataIndex: 'taxFee',
        }
      ];

      let params = this.params.fApi.formData();
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.orderId = this.orderId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await getTableDetailPage(params);
      if (code === '1') {
        // 处理自定义金额数据
        let otherSalary = {};
        data.content.forEach(item => {
          if (Object.keys(item.otherSalary).length > 0) {
            otherSalary = item.otherSalary;
            for (const key in item.otherSalary) {
              item[key] = item.otherSalary[key]
            }
          }
        })
        if (Object.keys(otherSalary).length > 0) {
          let len = Object.keys(otherSalary).length;
          this.tableWidth = 1600 + (len * 100);
          for (const key in otherSalary) {
            this.table.columns.push({
              title: key,
              dataIndex: key,
            })
          }
        }
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    // 导出发薪明细
    exportSalary() {
      let params = this.params.fApi.formData();
      params.orderId = this.orderId;
      exportExcelDetails(params).then(res => {
        const blob = new Blob([res]);
        const fileName = '发薪明细详情.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 下载模板
    downloadSalary() {
      downTemplate(this.enterpriseId).then(res => {
        const blob = new Blob([res]);
        const fileName = '计薪人员模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 导入表单
    importSalary() {
      this.$refs.fileExcel.click();
    },
    importSalaryHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("orderId", _this.orderId);
        formData.append("file", file);
        importSalaryDetail(formData).then((res) => {
          if (res.code == 1) {
            _this.importVisible = false;
            _this.$message.success('操作成功');
            _this.loadTable(true);
          }
        })
      }
    },
    // 删除计薪人员
    async delSalary() {
      let params = {
        detailIds: this.selectedRowKeys
      }
      const { code } = await batchDeleteSalary(params);
      if (code === '1') {
        this.$message.success('操作成功');
        this.selectedRowKeys = [];
        this.loadTable(true);
      }
    },
    addLoad() {
      this.loadTable(true);
    },
    reset() {
      this.params.fApi.resetFields();
      this.loadTable(true);
    },
    goBack() {
      this.$router.back();
    }
  }
}
</script>
<style lang="less"></style>